//
//  UITextView+Emoticon.swift
//  02.表情键盘
//
//  Created by yaochunlin on 16/4/26.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit

extension UITextView {
    
    //print("获取text文本 \(textView.attributedText)")
    //获取属性文本的每一段
    func emoticonText() -> String {
        
        
        
        var strM = ""
        
        //遍历获取属性文本的每一段
        attributedText.enumerateAttributesInRange(NSRange.init(location: 0, length: attributedText.length), options: []) { (dict, range, _) in
            
            //判断是否为附件
            if let attachment = dict["NSAttachment"] as? YCLTextAttachment {
                
                strM += attachment.chs!
            }else{
                
                let text = (self.attributedText.string as NSString).substringWithRange(range)
                
                strM += text
            }
            //
            //            print("dict:\(dict)")
            //            print("range:\(range)")
            //            print("----------")
            
        }
        
        //        print("strm:\(strM)")
        return strM
    }
    
    //将模型内容添加到textview上
    func insertEmoticon(emotion: YCLEmoticonModel) {
        
        //1.emoji表情
        if let emoji = emotion.emoji {
            
            insertText(emoji)
            return
        }
        
        //2.图片表情
        
        if let pngPath = emotion.pngPath {
            
            //将图片放到附件中，附件可以添加到属性文本，textview可以显示属性文本
            let attachment = YCLTextAttachment()
            attachment.image = UIImage.init(named: pngPath)
            attachment.chs = emotion.chs
            
            //获取文本高度
            let height = font?.lineHeight ?? 10
            
            //设置附件的大小
            attachment.bounds = CGRect.init(x: 0, y: -4, width: height, height: height)
            
            //属性文本并设置属性文本font
            let attrString = NSMutableAttributedString.init(attributedString: NSAttributedString.init(attachment: attachment))
            attrString.addAttribute(NSFontAttributeName, value: (font)!, range: NSRange.init(location: 0, length: 1))
            
            //获取textview现有文本
            let attrStringM = NSMutableAttributedString.init(attributedString: attributedText)
            
            //光标位置
            let currentSelectedRange = selectedRange
            
            
            //替换属性文本到对应的位置
            attrStringM.replaceCharactersInRange(currentSelectedRange, withAttributedString: attrString)
            
            
            attributedText = attrStringM
            
            //重新设置光标位置
            selectedRange = NSRange.init(location: (currentSelectedRange.location) + 1, length: 0)
            
        }
    }
    
    
}
